<?php


namespace app\common\logic;


use app\common\model\Columns;

class Shopowner extends Base
{
    /**
     * 重组提交数据
     * @param  array $data 请求的数据
     */
    public function recombine($data)
    {
        if (isset($data['id']) && $data['id']) {
            // 编辑
            if (isset($data['password']) && $data['password']) {
                $data = $this->validPass($data);
            } else {
                unset($data['password']);
            }
        } else {
            // 添加
            if (!trim($data['username'])) {
                exception('请输入用户名');
            } elseif (!preg_match('/^[a-zA-Z0-9_][a-zA-Z0-9_]{5,}$/', $data['username'])) {
                exception('请输入正确的用户名');
            }

            $data = $this->validPass($data);

            $data['shop_id'] = isset($data['shop_id']) ? $data['shop_id'] : 1;
        }
        if (!isset($data['role_id']) && !$data['role_id']) {
            exception('请选择所属角色');
        }
        $data['status'] = isset($data['status']) ? $data['status'] : 0;

        if (isset($data['admin_columns'])) {
            $temp = [];
            foreach ($data['admin_columns'] as $v) {
                $info     = Columns::field('super_column_ids,sub_column_ids')->where('id', $v)->find();
                $superIds = $info['super_column_ids'] ? explode(',', $info['super_column_ids']) : '';
                $subIds   = $info['sub_column_ids'] ? explode(',', $info['sub_column_ids']) : '';

                if ($superIds) {
                    foreach ($superIds as $id) {
                        if (!in_array($id, $temp)) {
                            $temp[] = $id;
                        }
                    }
                }
                if ($subIds) {
                    foreach ($subIds as $id) {
                        if (!in_array($id, $temp)) {
                            $temp[] = $id;
                        }
                    }
                }
                if (!in_array($v, $temp)) {
                    $temp[] = $v;
                }
            }
            sort($temp);
            $data['admin_columns'] = $temp;
        } else {
            $data['admin_columns'] = [];
        }
        return $data;
    }

    /**
     * 用户密码验证
     * @param  array $data 请求的信息
     */
    private function validPass($data)
    {
        if (!trim($data['password'])) {
            exception('请输入密码');
        } elseif (!preg_match('/^[a-zA-Z0-9_@][a-zA-Z0-9_@]{5,}$/', $data['password'])) {
            exception('请输入正确的密码');
        }

        if (!trim($data['password_confirm'])) {
            exception('请输入确认密码');
        } elseif ($data['password_confirm'] != $data['password']) {
            exception('两次密码必须相同');
        }

        $data['salt'] = unid(8);
        $data['password'] = salt_pass($data['password'], $data['salt']);
        return $data;
    }
    public function getModel()
    {
        return (new \app\common\model\Users());
    }
}